<template>
    <div>
        <div class="margin-bottom-20 flex" v-if="!isFromRenterDetail">
            <i-button type="primary" @click="handleSearch">刷新</i-button>
            <i-button type="primary" style="margin-left: auto" @click="handleAuthBath" >租客批量授权</i-button>
        </div>

        <Table :data="tableData" :columns="columns" :loading="loading"></Table>

        <div class="text-center margin-top-20" v-if="!isFromRenterDetail">
            <Page
                show-total
                :current.sync="pagination.current"
                :total="pagination.total"
                :page-size="pagination.limit"
                @on-change="handlePageChange"
            />
        </div>

        <auth-bath
            :show.sync="authVisible"
            :room-id="roomId"
            :device-id="deviceInfo.id"
            @refresh="handlePageChange"
            v-if="!isFromRenterDetail">
        </auth-bath>
    </div>
</template>

<script>
    import debouce from 'lodash/debounce'
import { http, api } from '@/libs/http'
import { date } from '@/libs/date'
import authBath from '../components/m3-auth-batch'

export default {
      name: 'm3-auth-history',
      props: {
        deviceInfo: Object,
        roomId: Number,
        isFromRenterDetail: { // 是否是从租客详情进来的租客
          type: Boolean,
          default: false
        },
        value: {
          type: [Array, Object]
        }
      },
      components: {
        authBath
      },
      data () {
        return {
          loading: false,
          submiting: false,
          pagination: {
            current: 1,
            total: 0,
            limit: 20
          },
          authVisible: false,
          tableData: [],
          columns: [
            {
              title: '编号',
              align: 'center',
              render: (h, { row }) => {
                const { id } = row

                return (
                  <div>
                    <i-button size='small' style="margin-right:5px">远程</i-button>
                    <span>{id}</span>
                  </div>
                )
              }
            },
            { title: '状态', key: 'status', align: 'center' },
            {
              title: '授权有效期',
              align: 'center',
              render: (h, { row: { begin_time, end_time } }) => {
                return <div>
                  <div>{date(begin_time, 'YYYY-MM-DD HH:mm')}</div>
                  <div>{date(end_time, 'YYYY-MM-DD HH:mm')}</div>
                </div>
              }
            },
            { title: '姓名', key: 'user', align: 'center' },
            { title: '发送给', key: 'relation_phone', align: 'center' },
            { title: '备注', align: 'center', render: (h, { row }) => <span>{row.state === 0 ? '删除授权成功' : '添加授权成功'}</span> },
            {
              title: '操作',
              align: 'center',
              render: (h, p) => {
                if (p.row.state !== 1) return null
                const { device_id, id, room_id } = p.row
                const params = this.isFromRenterDetail ? [room_id, device_id, id] : [this.roomId, this.deviceInfo.id, id]
                return <i-button size='small' onClick={() => { this.handleUnauth(params) }}>取消授权</i-button>
              }
            }
          ],
          statusMap: {
            0: '已失效',
            1: '已生效',
            2: '已过期',
            3: '将生效'
          }
        }
      },
      created () {
        if (!this.isFromRenterDetail) { // 如果是从租客详情进入
          this.initData(true)
        } else {
          this.handleData(this.value)
        }
      },
      methods: {
        getQuery () {
          const { current, limit } = this.pagination
          return {
            limit,
            offset: (current - 1) * limit
          }
        },
        handleSearch: debouce(function () {
          this.pagination.current = 1
          this.initData(true)
        }, 200),
        handlePageChange () {
          this.initData(false)
        },
        handleAuthBath () {
          this.authVisible = true
        },
        handleUnauth (id) {
          this.$Modal.confirm({
            title: '提示',
            content: '确定解除该授权?',
            onOk: () => {
              this.unauth(id)
            }
          })
        },

        async unauth (params) {
          if (this.submiting) return
          this.submiting = true
          const loading = this.$Message.loading('提交中...')
          try {
            const res = await http.req(api.m3_auth_del, params, null)
            if (res) {
              this.$Message.success('取消授权成功')
              this.handlePageChange()
            }
          } catch (err) {
            console.log(err)
          } finally {
            loading && loading()
            this.submiting = false
          }
        },
        async initData (recount = false) {
          try {
            this.loading = true
            const { roomId, deviceInfo: { id } } = this
            const ids = [ roomId, id ]
            const query = this.getQuery()
            if (recount) this.fetchCount(ids, query)
            const res = await http.req(api.m3_auth_records, ids, query)
            if (res) {
              this.handleData(res.rows)
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        },

        handleData (rows) {
          this.tableData = rows.map(item => {
            item.status = this.statusMap[item.state] || '未知'
            item.user = `[租客]${item.relation_name}`

            return item
          })
        },

        async fetchCount (ids, query) {
          try {
            const res = await http.req(api.m3_auth_records_count, ids, query)
            if (res) this.pagination.total = res.count
          } catch (err) {
            console.log(err)
          }
        }
      }
    }
</script>